package com.tina.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.tina.config.AlipayConfigInfo;
import com.tina.entity.AlipayBean;
import com.tina.entity.AlipayRefun;
import com.tina.service.file.ISysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 支付宝支付工具类
 *
 * @author Tina
 */
@Component
public class AliPayUtil {
    // 1、获得初始化的AlipayClient
    private final String serverUrl = AlipayConfigInfo.gatewayUrl;
    private final String appId = AlipayConfigInfo.app_id;
    private final String privateKey = AlipayConfigInfo.merchant_private_key;
    private final String format = "json";
    private final String charset = AlipayConfigInfo.charset;
    private final String alipayPublicKey = AlipayConfigInfo.alipay_public_key;
    private final String signType = AlipayConfigInfo.sign_type;
    private final String returnUrl = AlipayConfigInfo.return_url;
    private final String notifyUrl = AlipayConfigInfo.notify_url;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 生成二维码支付
     *
     * @param outTradeNo  商户订单号
     * @param totalAmount 总金额
     * @param goodsName   商品名称
     * @return
     * @throws AlipayApiException
     */
    public String codePay(String outTradeNo, BigDecimal totalAmount, String goodsName) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        //创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"total_amount\":\"" + totalAmount + "\"," +
                "\"subject\":\"" + goodsName + "\"," +
                "\"timeout_express\":\"29m\"}"); //订单允许的最晚付款时间 提前一分钟失效
        request.setNotifyUrl(AlipayConfigInfo.notify_url);
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        JSONObject res = JSON.parseObject(response.getBody());
        Map re = (Map) res.get("alipay_trade_precreate_response");
        // 文件中的LOGO
        File file = ResourceUtils.getFile("classpath:static/assets/img/logo/tina.png");

        File qr_code = ZxingUtils.getQRCodeLogoImge(re.get("qr_code").toString(), 250, localFilePath + outTradeNo + ".png", file);
        String uploadFile = sysFileService.uploadFile(FileUtils.getMultipartFile(qr_code));
        return uploadFile;
    }


    /**
     * 支付接口
     *
     * @param alipayBean 封装的支付宝入参
     * @return 返回支付结果
     * @throws AlipayApiException 抛出异常
     */
    public String pay(AlipayBean alipayBean) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
        // 3、请求支付宝进行付款，并获取支付结果

        return alipayClient.pageExecute(alipayRequest).getBody();
    }


    /**
     * 支付宝退款 接口
     *
     * @param alipayRefun
     * @return
     * @throws AlipayApiException
     */
    public Boolean alipayRefund(AlipayRefun alipayRefun) throws Exception {
        IDWorker idWorker = new IDWorker(2, 3);
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,
                appId, privateKey, "json", "GBK",
                alipayPublicKey, "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + alipayRefun.getOutTradeNo() + "\"," +
                "\"trade_no\":\"" + alipayRefun.getTradeNo() + "\"," +
                "\"refund_amount\":\"" + alipayRefun.getRefundAmount() + "\"," +
                "\"out_request_no\":\"" + idWorker.nextId() + "\"," +
                "      \"goods_detail\":[{" +
                "\"goods_name\":\"" + alipayRefun.getGoodsName() + "\"," +
                "\"quantity\":\"" + alipayRefun.getQuantity() + "\"" +
                "        }]" +
                "}");

        AlipayTradeRefundResponse response = alipayClient.execute(request);
        return response.isSuccess();
    }

}
